from django.db import models
from django.db.models import Manager


class SellerManager(Manager):
    """自定义管理器类"""

    def get_name(self, id):
        """根据id查找name"""
        seller = Seller.objects.filter(id=id).first()
        if seller:
            return seller.name
        else:
            return None


class Seller(models.Model):
    name = models.CharField(max_length=64)
    password = models.CharField(max_length=64)
    nickname = models.CharField(max_length=64, null=True)
    gender = models.CharField(max_length=1, null=True)
    age = models.IntegerField(null=True)
    # ImageField图片路径 ?
    picture = models.ImageField(null=True)
    phone = models.CharField(max_length=11, null=True)
    address = models.CharField(max_length=64, null=True)
    # EmailField自带邮箱格式验证
    email = models.EmailField(max_length=64, null=True)
    createtime = models.DateTimeField(null=True)

    def __str__(self):
        return self.name

    # 修改表名，默认的名字是 “app的名字_类名” 小写  app01_seller
    class Meta:
        db_table = "seller"

    # 注册管理器对象
    objects = SellerManager()


class Store(models.Model):
    """store店铺"""
    name = models.CharField(max_length=64)
    description = models.TextField(null=True)
    address = models.CharField(max_length=64, null=True)
    picture = models.ImageField(null=True)
    # seller_id = models.IntegerField()
    seller = models.OneToOneField(to="Seller", on_delete=models.CASCADE)  # Store + seller_id    Seller + bg(Store类名的小写)
    goodstypes = models.ManyToManyField(to="GoodsType")
    lasttime = models.DateTimeField(null=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "store"


class GoodsType(models.Model):
    """store店铺"""
    name = models.CharField(max_length=64)
    description = models.TextField(null=True)
    picture = models.ImageField(null=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "goodstype"


class Goods(models.Model):
    """store店铺"""
    name = models.CharField(max_length=64)
    price = models.IntegerField(null=True)
    number = models.IntegerField(null=True)
    sale = models.IntegerField(null=True)
    picture = models.ImageField(null=True)
    description = models.TextField(null=True)
    detail = models.TextField(null=True)
    producttime = models.DateField(null=True)
    shelfife = models.IntegerField(null=True)
    unite = models.CharField(max_length=64)
    # store_id = models.IntegerField(null=True)
    # goodstype_id = models.IntegerField(null=True)
    store = models.ForeignKey(to="Store", on_delete=models.CASCADE)  # Goods + store_id    Store + goods_set
    goodstype = models.ForeignKey(to="GoodsType", on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "goods"
